<style scoped>
.news-outer{width: 500px;padding: 20px;background: var(--bg);}
.news-outer li{width: 100%;position: relative;padding: 10px;background: #fff;border-top: 01px dashed var(--sm_bg);}
.news-outer li:first-child{border-top: none;}
.news-outer li img{margin: 10px;width: 60px;height: 60px;object-fit: cover;}
.news-outer li>.content{padding-right: 10px;}
.news-outer li>i{transform: rotate(45deg);position: absolute;top: 0;right: 0;text-align: center;width: 1.5em;line-height: 1.5;cursor: pointer;}
</style>
<template>
  <forms ref="forms" :config="config" @submit:forms="onsubmit" :btns="btns">
    <template v-slot:hr="{row}">
      ---------------------------{{row.value}}---------------------------
    </template>
    <template v-slot:news_data="{row}">
      <input type="hidden" :name="row.name" :value="row.value">
      <ul class="news-outer">
        <li v-for="(item,i) in JSON.parse(row.value)" class="flex">
          <div class="content max">
            <h3>{{item.Title}}</h3>
            <p>{{item.Description}}</p>
          </div>
          <img :src="item.PicUrl" >
          <i ico="s94" class="ico-jia" @click="delete_news_item(row,i)"></i>
        </li>
      </ul>
      <json_param :config="row.config" v-model:value="last_news_json"></json_param>
      <el-button size="small" type="primary" @click="add_news(row)">添加</el-button>
    </template>
  </forms>
</template>

<script>
import {ajax} from "@/js/api_tool.js";
import {iframe} from "@/js/tool.js";
import json_param from "@/components/auto_import/UnifyParam/json_param.vue";
import {_config} from "@/js/s94_tool.js";
import s94Mjs from "s94-js";

export default {
  components: {json_param},
  props: ['__iframe'],
  data(){
    let id = this.$get('id'), btns = undefined;

    let type_map = _config('status_alias_map.message_reply.type');
    let return_type_map = {text:'文本',image:'图片素材',voice:'语音素材',video:'视频素材',music:'音乐',news:'图文'};
    let forms_config = {
      type: {label:'类型',name:'type',type:'select_one',config:type_map,tips:''},
      rule_type: {label:'适配规则',name:'rule_type',type:'select_one',config:[],tips:''},
      rule_value: {label:'规则内容',name:'rule_value',type:'text_one',tips:''},

      hr: {label:'分割线',type:'hr',tips:'',value:'以下为回复内容的设定'},

      return_type: {label:'消息类型',name:'return_type',type:'select_one',config:return_type_map,tips:'', value:'text'},
      return_data: {label:'消息数据',name:'return_data',type:'text_more',tips:''},
      return_extend: {label:'消息扩展',name:'return_extend',type:'json_param',config:[],tips:'',remove:true},
    }
    if (id){
      forms_config.create_time = {label:'创建时间',name:'create_time',tips:''};
    }
    if (this.$get('is_info')){
      s94Mjs.each(forms_config, function (row){ row.is_info = true; });
      btns = [];
    }
    return {
      id: id,
      btns: btns,
      config: forms_config,
      last_news_json: '{}',
    }
  },
  methods: {
    onsubmit(formData){
      let url = this.id ? `/admin/message_reply/edit?id=`+this.id : '/admin/message_reply/add';
      ajax({url:url, method:'POST', data:formData}, (res)=>{
        if (this.__iframe){
          iframe.exe('message_reply/index', '$refs.list_url.list');
          iframe.hide('message_reply/edit');
          if (!this.id) this.$refs['forms'].init();
        }else {
          this.$router.push('index');
        }
      }, (res)=>{
        if (res.errors) this.$refs['forms'].errors = res.errors;
      })
    },
    delete_news_item(row, i){
      let value_arr = JSON.parse(row.value);
      this.$confirm('是否确定删除','操作确定').then(()=>{
        value_arr.splice(i,1);
        row.value = JSON.stringify(value_arr);
      }).catch(()=>{})
    },
    add_news(row){
      let last_news = JSON.parse(this.last_news_json);
      if (!last_news.Title) return this.$msgbox({message:'标题不能为空'});
      if (!last_news.Description) return this.$msgbox({message:'简介不能为空'});
      if (!last_news.PicUrl) return this.$msgbox({message:'头图不能为空'});
      if (!/^https?:\/\/.+/.test(last_news.Url)) return this.$msgbox({message:'请填写合理的跳转链接'});
      let value_arr = JSON.parse(row.value);
      value_arr = value_arr instanceof Array ? value_arr : [];
      value_arr.push(last_news);
      row.value = JSON.stringify(value_arr);
      this.last_news_json = '{}';
    },
  },
  watch: {
    'config.type.value'(v, oldV){
      let map = [
        {label:'适配规则', config:{'eq':'全等','like':'包含','regexp':'正则规则'} },
        {label:'事件名称', config:{'subscribe':'订阅','click':'点击','scancode_push':'扫码推事件','scancode_waitmsg':'扫码待回复','pic_sysphoto':'拍照发图','pic_photo_or_album':'拍照或相册发图','pic_weixin':'微信相册发图','location_select':'发送位置'} },
      ]
      let config = map[v] || map[0];
      this.config.rule_type.label = config.label;
      this.config.rule_type.config = config.config;
      if (!(this.config.rule_type.value in config.config)){
        this.config.rule_type.value = '';
      }
    },
    'config.rule_type.value'(v, oldV){
      let tips = '';
      switch (v){
        case 'eq':case 'like': tips='检索的文本';break;
        case 'regexp': tips='正则规则的字符串(不带首尾的分隔符)，例如验证手机号码：^1\\d{10}$';break;
        default: tips='事件的 KEY 值';break;
      }
      this.config.rule_value.tips = tips;
      this.config.rule_value.remove = (v==='subscribe');
    },
    'config.return_type.value'(v, oldV){
      let app = this;
      //return_data的配置
      let return_data_config = {label:'消息数据',name:'return_data',type:'text_more',value:'',tips:'',remove:false};
      if (~['image','voice','video','music'].indexOf(v)){
        return_data_config.label = v=='music' ? '缩略图素材' : '选择素材';
        return_data_config.type = 'wechat_file';
        return_data_config.config = v=='image'||v=='music' ? 'jpg,jpeg,png,gif' : (v=='voice'?'mp3':'mp4');
      }else if(v=='news') {
        return_data_config.remove = true;
      }
      app.config.return_data = return_data_config;
      //return_extend的配置
      let return_extend_config = {label:'消息扩展',name:'return_extend',type:'json_param',config:[],value:'{}',tips:'',remove:false};
      if (~['text','image','voice'].indexOf(v)){ //text,image,voice 不显示return_extend
        return_extend_config.remove = true;
      }else {
        return_extend_config.config = [
          {label:'标题',name:'Title',type:'text_one',tips:''},
          {label:'简介',name:'Description',type:'text_one',tips:''},
        ];
        switch (v){
          case 'music':{
            return_extend_config.config.push(
                {label:'音乐url',name:'MusicUrl',type:'file',config:'mp3',protocol:'http',tips:''},
                {label:'音乐url(HQ)',name:'HQMusicUrl',type:'file',config:'mp3',protocol:'http',tips:''}
            );
          }break;
          case 'news':{
            return_extend_config.config.push(
                {label:'图片',name:'PicUrl',type:'file',config:'jpg,jpeg,png,gif',protocol:'http',tips:''},
                {label:'跳转链接',name:'Url',type:'text_one',tips:''}
            );
            return_extend_config.label = '消息内容';
            return_extend_config.tips = '对于文本消息的回复，最多只能回复一条图文消息。';
            return_extend_config.type = 'news_data';
          }break;
        }
      }
      app.config.return_extend = return_extend_config;
    },
  },
  mounted() {
    let app = this;
    if (!this.__iframe) window['app'] = this;
    if (this.id) {
      ajax({url:'/admin/message_reply/info?id='+this.id, cache:true}, (res)=>{
        this.$refs['forms'].init(res.data);
        setTimeout(function (){
          app.config.return_extend.value = res.data.return_extend;
          app.config.return_data.value = res.data.return_data;
        },200)
        return false;
      }, ()=>{
        if (this.__iframe){
          iframe.remove('message_reply/edit');
        }else {
          this.$router.push('index');
        }
      })
    }

    //其他初始化操作
  }
}
</script>
